package com.salt.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.salt.common.Result;
import com.salt.entity.User;
import com.salt.entity.UserInfo;
import com.salt.service.UserInfoService;
import com.salt.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * 用户信息控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/user-info")
@RequiredArgsConstructor
public class UserInfoController {

    private final UserInfoService userInfoService;

    /**
     * 保存或更新用户信息
     * @param userInfo 用户信息
     * @return 处理结果
     */
    @PostMapping("/save")
    public Result<UserInfo> saveUserInfo(@RequestBody UserInfo userInfo) {
        log.info("接收到保存用户信息请求：{}", userInfo);
        
        try {
            UserInfo savedUser = userInfoService.saveOrUpdateUserInfo(userInfo);
            return Result.success(savedUser);
        } catch (IllegalArgumentException e) {
            log.warn("保存用户信息参数错误：{}", e.getMessage());
            return Result.error(400, e.getMessage());
        } catch (Exception e) {
            log.error("保存用户信息失败", e);
            return Result.error("保存失败：" + e.getMessage());
        }
    }

   /**
     * 根据手机号查询用户信息
     * @param current 当前页
     * @param size 每页大小
     * @param status 状态(0-禁用,1-启用)，不传则查询所有
     * @return 用户信息
     */
    @GetMapping("/get")
    public Result<IPage<UserInfo>> getUserByInviteCode(
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size,
            @RequestParam(required = false) Integer status) {
        try {
            User user = UserContext.getUser();
            if (user == null) {
                return Result.error("用户未登录");
            }
            Page<UserInfo> page = new Page<>(current, size);
            IPage<UserInfo> userInfoPage = userInfoService.pageQueryByInviteCode(page, user.getInviteCode(), status);
            return Result.success(userInfoPage);
        } catch (Exception e) {
            log.error("查询用户信息失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户余额总数
     * @return 余额总数
     */
    @GetMapping("/total-balance")
    public Result<BigDecimal> getTotalBalance() {
        try {
            User user = UserContext.getUser();
            if (user == null) {
                return Result.error("用户未登录");
            }
            BigDecimal totalBalance = userInfoService.getTotalBalance(user.getInviteCode());
            return Result.success(totalBalance);
        } catch (Exception e) {
            log.error("获取余额总数失败", e);
            return Result.error("获取失败：" + e.getMessage());
        }
    }
} 